'use strict';

const log4js = require('log4js');
const fs = require('fs');
const path = require('path');
const koaRouter = require('koa-router');
const koaJson = require('koa-json');
const RP = require('request-promise');
const Util = require('../util.js');

const router = koaRouter();
const logger = log4js.getLogger();

// router.use(koaJson({pretty: true}));
router.get('/app-web/odata/:bo/$metadata', function *(next) {
  this.set('content-type', 'application/xml;');
  this.body =
    `<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:sap="http://www.sap.com/Protocols/SAPData">
	<edmx:DataServices m:DataServiceVersion="2.0">
		<Schema Namespace="sme" xml:lang="en" sap:schema-version="0000" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
			<EntityType Name="data" sap:content-version="1">
			</EntityType>
			<EntityContainer Name="MYSAMPLE_Entities" m:IsDefaultEntityContainer="true">
				<EntitySet Name="dataset" EntityType="data" sap:content-version="1"/>
			</EntityContainer>
		</Schema>
	</edmx:DataServices>
</edmx:Edmx>
`;

  yield next;
});

router.get('/app-web/odata/:bo/data/$count', function *(next) {
  let res = yield RP({
    uri: `${Util.getHost()}/app-web/ui.svc`,
    qs: Object.assign({}, JSON.parse(this.request.query._ext_ || "{}"), {
      '$count': '',
      '$select': undefined,
      '$filter': this.request.query['$filter'] || undefined,
    }),
    headers: this.request.header,
    json: true
  });

  this.body = res;

  this.set('content-type', 'text/plain;charset=utf-8');
  //this.set('DataServiceVersion', '2.0');
  this.set('dataserviceversion', '2.0');


  yield next;
});


router.get('/app-web/odata/:bo/data', function *(next) {
  let bo = this.params.bo;

  let res = yield RP({
    uri: `${Util.getHost()}/app-web/ui.svc`,
    qs: Object.assign({}, JSON.parse(this.request.query._ext_ || "{}"), {
      '$top': this.request.query['$top'] || undefined,
      '$limit': this.request.query['$limit'] || undefined,
      '$orderby': this.request.query['$orderby'] || undefined,
      '$filter': this.request.query['$filter'] || undefined,
    }),
    headers: this.request.header,
    json: true
  });


  this.body = {
    d: {
      results: res.map(d => {
        return Object.assign({}, d, {
          __metadata: {
            id: `/odata/${bo}/BO(${d.id})`,
            uri: `/odata/${bo}/BO(${d.id})`,
            type: `data`
          }
        });
      })
    }
  };

  this.set('content-type', 'application/json;charset=utf-8');
  this.set('dataserviceversion', '2.0');


  yield next;
});

module.exports = router;
